package com.jlcindia.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

public class SIDGenerator implements IdentifierGenerator{
	public Serializable generate(SessionImplementor si,Object obj) throws HibernateException{
		String sid = "JLC-001";
		Transaction tx = null;
		try {
			SessionFactory sf = HibernateUtil.getSessionFactory();
			Session session = sf.openSession();
			tx = session.beginTransaction();
			String hql1 = "from Student stu";
			Query q1 = session.createQuery(hql1);
			List l1 = q1.list();
			if (l1.size() != 0) {
				String hql = "select max(sid) from Student stu";
				Query q = session.createQuery(hql);
				List list = q.list();
				System.out.println(list.size());
				Object o = list.get(0);
				System.out.println(o);
				String id = "";
				id = o.toString();
				String p2 = id.substring(6);
				int x = Integer.parseInt(p2);
				x = x + 1;
				if (x <= 9) {
					sid = "JLC-00" + x;
				} else if (x <= 99) {
					sid = "JLC-0" + x;
				} else {
					sid = "JLC-" + x;
				}
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		}
		return sid;
	}

}
